<template>
  <div class="bone-density-container">
    <el-row :gutter="20">
      <!-- 左侧PDF预览区域 -->
      <el-col :span="12">
        <div class="pdf-viewer-container">
          <div class="pdf-controls">
            <el-button-group>
              <el-button
                size="small"
                @click="prevFile"
                :disabled="currentFileIndex === 0">
                上一个文件
              </el-button>
              <el-button
                size="small"
                @click="nextFile"
                :disabled="currentFileIndex === pdfFiles.length - 1">
                下一个文件
              </el-button>
            </el-button-group>

            <el-button
              size="small"
              type="primary"
              @click="triggerFileUpload"
              class="upload-btn">
              上传PDF文件
            </el-button>

            <input
              type="file"
              ref="fileInput"
              @change="handleFileUpload"
              multiple
              accept=".pdf"
              style="display: none">
          </div>

          <div class="pdf-viewer-wrapper">
            <pdf
              v-for="page in numPages"
              :key="page"
              :src="pdfUrl"
              :page="page"
              class="pdf-page">
            </pdf>

            <div class="page-controls">
              <el-button
                size="mini"
                @click="prevPage"
                :disabled="currentPage === 1">
                上一页
              </el-button>
              <span>第 {{ currentPage }} 页 / 共 {{ numPages }} 页</span>
              <el-button
                size="mini"
                @click="nextPage"
                :disabled="currentPage === numPages">
                下一页
              </el-button>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 右侧表单区域 -->
      <el-col :span="12">
        <div class="report-form-container">
          <h2 class="form-title">骨密度数据报告</h2>
          <div slot="footer" class="dialog-footer" style="text-align: right">
            <el-button type="primary" @click="goToBmdStrategy" >跳转到骨密度策略报告</el-button>
          </div>

          <el-form
            ref="reportForm"
            :model="reportData"
            label-width="100px"
            class="report-form">

            <el-form-item label="基本信息" class="section-title"></el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名">
                  <el-input v-model="reportData.name" readonly></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline" @click="openExpandDialog('name', '姓名')"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄">
                  <el-input v-model="reportData.age" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-input v-model="reportData.gender" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="床号">
                  <el-input v-model="reportData.bedNumber" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="门诊/住院号">
                  <el-input v-model="reportData.patientNumber" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请科室">
                  <el-input v-model="reportData.department" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检查医生">
                  <el-input v-model="reportData.doctor" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检查时间">
                  <el-input v-model="reportData.examTime" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="检查所见" class="section-title"></el-form-item>
            <el-form-item>
              <el-input
                type="textarea"
                :rows="4"
                v-model="reportData.findings"
                readonly>
              </el-input>
            </el-form-item>

            <el-form-item label="报告结论" class="section-title"></el-form-item>
            <el-form-item>
              <el-input
                type="textarea"
                :rows="4"
                v-model="reportData.conclusion"
                readonly>
              </el-input>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="审核医生">
                  <el-input v-model="reportData.reviewDoctor" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布时间">
                  <el-input v-model="reportData.publishTime" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-col>
      <!-- 放大编辑对话框 -->
      <el-dialog
        :title="expandDialog.title"
        :visible.sync="expandDialog.visible"
        class="fullscreen-dialog"
        :append-to-body="true">
        <el-input
          v-if="expandDialog.isTextarea"
          type="textarea"
          :autosize="{ minRows: 8, maxRows: 12 }"
          v-model="expandDialog.value"
          class="fullscreen-textarea">
        </el-input>
        <el-input
          v-else
          v-model="expandDialog.value"
          class="fullscreen-input">
        </el-input>
        <span slot="footer" class="dialog-footer">
        <el-button @click="expandDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="confirmExpandEdit">确 定</el-button>
      </span>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: {
    pdf
  },
  data() {
    return {
      pdfFiles: [], // 存储上传的PDF文件
      currentFileIndex: -1, // 当前显示的PDF文件索引
      pdfUrl: null, // 当前显示的PDF文件URL
      numPages: 0, // 当前PDF的总页数
      currentPage: 1, // 当前显示的PDF页码
      // 弹框数据
      expandDialog: {
      visible: false,
        title: '',
        field: '',
        value: '',
        isTextarea: false
    },

      // 报告数据
      reportData: {
        name: '',
        age: '',
        gender: '',
        bedNumber: '',
        patientNumber: '',
        department: '',
        doctor: '',
        examTime: '',
        findings: '',
        conclusion: '',
        reviewDoctor: '',
        publishTime: ''
      }
    }
  },
  created() {
    this.fetchReportData()
  },
  methods: {
    openExpandDialog(field, title, isTextarea = false) {
      this.expandDialog = {
        visible: true,
        title: `编辑${title}`,
        field: field,
        value: this.reportData[field],
        isTextarea: isTextarea
      };
    },
    confirmExpandEdit() {
      this.reportData[this.expandDialog.field] = this.expandDialog.value;
      this.expandDialog.visible = false;
      this.$message.success('修改成功');
    },

    //跳转到骨密度策略报告页面
    goToBmdStrategy() {
      this.$router.push('/bmd/bmdStrategy')
    },
    // 触发文件上传
    triggerFileUpload() {
      this.$refs.fileInput.click()
    },

    // 处理文件上传
    handleFileUpload(event) {
      const files = Array.from(event.target.files)
      if (files.length === 0) return

      // 过滤非PDF文件
      const pdfFiles = files.filter(file => file.type === 'application/pdf')

      if (pdfFiles.length === 0) {
        this.$message.error('请上传PDF文件')
        return
      }

      // 添加到PDF文件列表
      this.pdfFiles = [...this.pdfFiles, ...pdfFiles]

      // 如果是第一个文件，直接显示
      if (this.currentFileIndex === -1 && this.pdfFiles.length > 0) {
        this.currentFileIndex = 0
        this.loadPdfFile(this.pdfFiles[0])
      }

      this.$message.success(`成功上传${pdfFiles.length}个PDF文件`)
    },

    // 加载PDF文件
    loadPdfFile(file) {
      const fileReader = new FileReader()

      fileReader.onload = () => {
        this.pdfUrl = fileReader.result

        // 获取PDF页数
        const loadingTask = pdf.createLoadingTask(this.pdfUrl)
        loadingTask.promise.then(pdf => {
          this.numPages = pdf.numPages
          this.currentPage = 1
        }).catch(err => {
          console.error('PDF加载错误:', err)
          this.$message.error('PDF文件加载失败')
        })
      }

      fileReader.readAsDataURL(file)
    },

    // 上一个PDF文件
    prevFile() {
      if (this.currentFileIndex > 0) {
        this.currentFileIndex--
        this.loadPdfFile(this.pdfFiles[this.currentFileIndex])
      }
    },

    // 下一个PDF文件
    nextFile() {
      if (this.currentFileIndex < this.pdfFiles.length - 1) {
        this.currentFileIndex++
        this.loadPdfFile(this.pdfFiles[this.currentFileIndex])
      }
    },

    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
      }
    },

    // 下一页
    nextPage() {
      if (this.currentPage < this.numPages) {
        this.currentPage++
      }
    },

    // 从后端获取报告数据
    async fetchReportData() {
      try {
        // 这里替换为实际的API调用
        const response = await this.$http.get('/api/bone-density-report')

        if (response.data && response.data.success) {
          this.reportData = {
            name: response.data.data.name || '',
            age: response.data.data.age || '',
            gender: response.data.data.gender || '',
            bedNumber: response.data.data.bedNumber || '',
            patientNumber: response.data.data.patientNumber || '',
            department: response.data.data.department || '',
            doctor: response.data.data.doctor || '',
            examTime: this.formatDate(response.data.data.examTime) || '',
            findings: response.data.data.findings || '',
            conclusion: response.data.data.conclusion || '',
            reviewDoctor: response.data.data.reviewDoctor || '',
            publishTime: this.formatDate(response.data.data.publishTime) || ''
          }
        }
      } catch (error) {
        console.error('获取报告数据失败:', error)
        this.$message.error('获取报告数据失败')
      }
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return ''

      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')

      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.bone-density-container {
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 40px);
  overflow-y: auto;
}

.pdf-viewer-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.pdf-controls {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-btn {
  margin-left: 10px;
}

.pdf-viewer-wrapper {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.pdf-page {
  margin-bottom: 10px;
  border: 1px solid #ddd;
}

.page-controls {
  margin-top: 10px;
  text-align: center;
}

.report-form-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.section-title {
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 5px;
}

.report-form {
  margin-top: 20px;
}
</style>
